<template>
  <div v-loading="loading" class="notification-list-container">
    <!-- 工具栏 -->
    <div class="toolbar">
      <div class="toolbar-left">
        <el-radio-group
          v-model="queryParams.isRead"
          size="small"
          @change="handleQuery"
        >
          <el-radio-button :value="undefined">全部</el-radio-button>
          <el-radio-button :value="0">未读</el-radio-button>
          <el-radio-button :value="1">已读</el-radio-button>
        </el-radio-group>
      </div>

      <div class="toolbar-right">
        <el-button
          v-if="hasUnreadNotifications"
          size="small"
          type="primary"
          link
          @click="handleMarkAllRead"
        >
          <el-icon><Check /></el-icon>
          全部已读
        </el-button>
        <el-button
          v-if="canBatchOperate"
          size="small"
          type="danger"
          link
          @click="handleClearRead"
        >
          <el-icon><Delete /></el-icon>
          清空已读
        </el-button>
      </div>
    </div>

    <!-- 通知列表 -->
    <div v-if="notificationList.records.length > 0" class="notifications-list">
      <div
        v-for="notification in notificationList.records"
        :key="notification.id"
        class="notification-item"
        :class="{ 'is-unread': notification.isRead === 0 }"
        @click="handleItemClick(notification)"
      >
        <!-- 未读指示器 -->
        <div v-if="notification.isRead === 0" class="unread-dot" />

        <!-- 头像 -->
        <div class="item-avatar">
          <!-- 聚合点赞通知：显示最新3个人的头像堆叠 -->
          <div v-if="isAggregatedLike(notification)" class="aggregated-avatars">
            <el-avatar
              v-for="(sender, index) in getDisplaySenders(notification)"
              :key="sender.userId"
              :size="32"
              :src="formatAvatarUrl(sender.avatar || '')"
              :icon="UserFilled"
              class="stacked-avatar"
              :style="{ zIndex: 3 - index }"
              @click.stop="handleUserClick(sender.userId)"
            />
          </div>
          <!-- 普通通知：显示单个头像 -->
          <el-avatar
            v-else
            :size="36"
            :src="formatAvatarUrl(notification.sender?.avatar || '')"
            :icon="UserFilled"
            @click.stop="handleUserClick(notification.sender?.userId)"
          />
        </div>

        <!-- 内容 -->
        <div class="item-content">
          <!-- 聚合点赞通知：显示多个名称 -->
          <div v-if="isAggregatedLike(notification)" class="content-text">
            <span class="sender-name">
              {{ getAggregatedSenderNames(notification) }}
            </span>
            <NotificationContent :notification="notification" />
          </div>
          <!-- 普通通知 -->
          <div v-else class="content-text">
            <span
              class="sender-name"
              @click.stop="handleUserClick(notification.sender?.userId)"
            >
              {{
                notification.sender?.nickName ||
                notification.sender?.userName ||
                "系统"
              }}
            </span>
            <NotificationContent :notification="notification" />
          </div>
        </div>

        <!-- 右侧信息 -->
        <div class="item-right">
          <span class="meta-time">{{
            formatTime(notification.createTime)
          }}</span>
          <div class="item-actions" @click.stop>
            <el-button
              v-if="notification.isRead === 0"
              size="small"
              text
              type="primary"
              @click="handleMarkAsRead(notification)"
            >
              <el-icon><Check /></el-icon>
            </el-button>
            <span v-else class="read-text">已读</span>
            <el-button
              v-if="canBatchOperate"
              size="small"
              text
              type="danger"
              @click="handleDeleteSingle(notification.id)"
            >
              <el-icon><Delete /></el-icon>
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 空状态 -->
    <el-empty v-else :description="emptyText" />

    <!-- 分页 -->
    <div v-if="notificationList.total > 0" class="pagination-wrapper">
      <el-pagination
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :total="notificationList.total"
        :page-sizes="[10, 20, 30, 50]"
        layout="total, sizes, prev, pager, next, jumper"
        background
        @current-change="handleQuery"
        @size-change="handleQuery"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, PropType } from "vue";
import { useRouter } from "vue-router";
import { ElMessage, ElMessageBox } from "element-plus";
import { Refresh, Check, UserFilled, Delete } from "@element-plus/icons-vue";
import {
  getNotificationListApi,
  getNotificationStatsApi,
  markNotificationAsReadApi,
  markAllNotificationsAsReadApi,
  deleteNotificationApi,
  batchDeleteNotificationsApi,
  clearReadNotificationsApi,
  NotificationType,
  type NotificationDetail,
  type PageResponse,
  type NotificationListQuery
} from "@/api/notification";
import { formatAvatarUrl } from "@/utils/avatar";
import { getTargetUrl } from "@/utils/notificationUtils";
import NotificationContent from "./NotificationContent.vue";

// Props
const props = defineProps({
  type: {
    type: String as PropType<NotificationType>,
    required: true
  }
});

// Emit
const emit = defineEmits(["refresh"]);

// Router
const router = useRouter();

// 状态
const loading = ref(false);
const selectedIds = ref<number[]>([]);
const selectAll = ref(false);

// 查询参数
const queryParams = ref<NotificationListQuery>({
  pageNum: 1,
  pageSize: 10,
  type: props.type,
  isRead: undefined
});

// 通知列表
const notificationList = ref<PageResponse<NotificationDetail>>({
  records: [],
  total: 0,
  size: 10,
  current: 1,
  pages: 0
});

// 是否可以批量操作(系统通知不允许删除)
const canBatchOperate = computed(() => {
  return props.type !== NotificationType.SYSTEM;
});

// 空状态文本
const emptyText = computed(() => {
  const typeMap: Record<NotificationType, string> = {
    [NotificationType.FOLLOW]: "暂无新粉丝通知",
    [NotificationType.LIKE]: "暂无点赞通知",
    [NotificationType.COLLECT]: "暂无收藏通知",
    [NotificationType.COMMENT]: "暂无评论通知",
    [NotificationType.REPLY]: "暂无回复通知",
    [NotificationType.MENTION]: "暂无@提及通知",
    [NotificationType.SYSTEM]: "暂无系统通知"
  };
  return typeMap[props.type] || "暂无通知";
});

// 是否为半选状态
const isIndeterminate = computed(() => {
  const selectedCount = selectedIds.value.length;
  const totalCount = notificationList.value.records.length;
  return selectedCount > 0 && selectedCount < totalCount;
});

// 是否有未读通知
const hasUnreadNotifications = computed(() => {
  return notificationList.value.records.some(item => item.isRead === 0);
});

// 加载通知列表
const loadNotificationList = async () => {
  loading.value = true;
  try {
    const response = await getNotificationListApi(queryParams.value);
    if (response.code === 200 && response.data) {
      notificationList.value = response.data;
    } else {
      ElMessage.error(response.message || "加载通知列表失败");
    }
  } catch (error: any) {
    console.error("加载通知列表失败:", error);
    ElMessage.error("加载通知列表失败");
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  loadNotificationList();
};

// 重置
const handleReset = () => {
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    type: props.type,
    isRead: undefined
  };
  selectedIds.value = [];
  selectAll.value = false;
  loadNotificationList();
};

// 全选/取消全选
const handleSelectAll = (checked: boolean) => {
  if (checked) {
    selectedIds.value = notificationList.value.records.map(item => item.id);
  } else {
    selectedIds.value = [];
  }
};

// 选择/取消选择单个通知
const handleSelectItem = (id: number) => {
  const index = selectedIds.value.indexOf(id);
  if (index > -1) {
    selectedIds.value.splice(index, 1);
  } else {
    selectedIds.value.push(id);
  }

  // 更新全选状态
  selectAll.value =
    selectedIds.value.length === notificationList.value.records.length;
};

// 刷新未读数量并触发全局事件
const refreshUnreadCount = async () => {
  try {
    const response = await getNotificationStatsApi();
    if (response.code === 200 && response.data) {
      // 触发全局事件，通知消息铃铛组件更新
      window.dispatchEvent(
        new CustomEvent("unread-count-update", {
          detail: {
            total: response.data.totalUnreadCount,
            follow: response.data.unreadFollowCount,
            like: response.data.unreadLikeCount,
            comment: response.data.unreadCommentCount,
            reply: response.data.unreadReplyCount,
            mention: 0, // 接口文档中没有mention统计
            system: response.data.unreadSystemCount
          }
        })
      );
    }
  } catch (error) {
    console.error("刷新未读数量失败:", error);
  }
};

// 删除单个通知
const handleDeleteSingle = async (id: number) => {
  try {
    await ElMessageBox.confirm("确定要删除这条通知吗？", "确认删除", {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    });

    const response = await deleteNotificationApi(id);
    if (response.code === 200) {
      ElMessage.success("删除成功");
      loadNotificationList();
      emit("refresh");
      // 刷新未读数量并通知消息铃铛组件
      refreshUnreadCount();
    } else {
      ElMessage.error(response.message || "删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("删除通知失败:", error);
      ElMessage.error("删除失败");
    }
  }
};

// 批量删除
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning("请先选择要删除的通知");
    return;
  }

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selectedIds.value.length} 条通知吗？`,
      "确认批量删除",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await batchDeleteNotificationsApi(selectedIds.value);
    if (response.code === 200) {
      ElMessage.success("批量删除成功");
      selectedIds.value = [];
      selectAll.value = false;
      loadNotificationList();
      emit("refresh");
      // 刷新未读数量并通知消息铃铛组件
      refreshUnreadCount();
    } else {
      ElMessage.error(response.message || "批量删除失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("批量删除通知失败:", error);
      ElMessage.error("批量删除失败");
    }
  }
};

// 全部标记为已读
const handleMarkAllRead = async () => {
  if (!hasUnreadNotifications.value) {
    ElMessage.info("没有未读通知");
    return;
  }

  try {
    await ElMessageBox.confirm(
      "确定要将所有未读通知标记为已读吗？",
      "确认操作",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "info"
      }
    );

    const response = await markAllNotificationsAsReadApi(props.type);
    if (response.code === 200) {
      ElMessage.success("已标记所有通知为已读");
      loadNotificationList();
      emit("refresh");
    } else {
      ElMessage.error(response.message || "标记已读失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("标记全部已读失败:", error);
      ElMessage.error("标记失败");
    }
  }
};

// 清空已读通知
const handleClearRead = async () => {
  try {
    await ElMessageBox.confirm(
      "确定要清空所有已读通知吗？此操作不可恢复！",
      "确认清空",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );

    const response = await clearReadNotificationsApi();
    if (response.code === 200) {
      ElMessage.success("清空已读通知成功");
      selectedIds.value = [];
      selectAll.value = false;
      loadNotificationList();
      emit("refresh");
      // 刷新未读数量并通知消息铃铛组件
      refreshUnreadCount();
    } else {
      ElMessage.error(response.message || "清空失败");
    }
  } catch (error: any) {
    if (error !== "cancel") {
      console.error("清空已读通知失败:", error);
      ElMessage.error("清空失败");
    }
  }
};

// 点击用户
const handleUserClick = (userId?: number) => {
  if (userId) {
    router.push(`/user/profile/${userId}`);
  }
};

// 点击通知项
const handleItemClick = (notification: NotificationDetail) => {
  // 如果未读，先标记为已读
  if (notification.isRead === 0) {
    handleMarkAsRead(notification);
  }

  // 使用工具函数构建目标 URL，优先使用 extraData 中的信息
  const targetUrl = getTargetUrl(notification);

  if (targetUrl) {
    router.push(targetUrl);
  } else if (notification.target?.url) {
    // 向后兼容：如果没有 extraData 但有 target.url，使用旧的跳转逻辑
    router.push(notification.target.url);
  }
};

// 标记已读
const handleMarkAsRead = async (notification: NotificationDetail) => {
  try {
    const response = await markNotificationAsReadApi(notification.id);
    if (response.code === 200) {
      notification.isRead = 1;
      emit("refresh");
    } else {
      ElMessage.error(response.message || "标记已读失败");
    }
  } catch (error: any) {
    console.error("标记已读失败:", error);
    ElMessage.error("标记已读失败");
  }
};

// ========== 点赞聚合通知相关处理 ==========

// 判断是否为聚合点赞通知
const isAggregatedLike = (notification: NotificationDetail): boolean => {
  return (
    notification.type === "LIKE" &&
    notification.senderCount !== undefined &&
    notification.senderCount > 0
  );
};

// 获取显示的发送者列表（最多3个）
const getDisplaySenders = (notification: NotificationDetail) => {
  if (!notification.senders) return [];
  return notification.senders.slice(0, 3);
};

// 获取剩余人数
const getRemainingCount = (notification: NotificationDetail): number => {
  const count = notification.senderCount || 0;
  const displayCount = getDisplaySenders(notification).length;
  return Math.max(0, count - displayCount);
};

// 获取聚合发送者名称（按照API文档格式）
const getAggregatedSenderNames = (notification: NotificationDetail): string => {
  const senders = getDisplaySenders(notification);
  const count = notification.senderCount || 0;

  if (count === 0) return "用户";

  if (count === 1) {
    // 单人点赞：张三
    return senders[0]?.nickName || "用户";
  } else if (count <= 3) {
    // 3人以内：张三、李四、王五
    return senders.map(s => s.nickName || "用户").join("、");
  } else {
    // 超过3人：张三、李四、王五
    return senders.map(s => s.nickName || "用户").join("、");
  }
};

// 格式化时间
const formatTime = (time: string): string => {
  if (!time) return "-";
  const date = new Date(time);
  const now = new Date();
  const diff = now.getTime() - date.getTime();

  const minute = 60 * 1000;
  const hour = 60 * minute;
  const day = 24 * hour;

  if (diff < minute) {
    return "刚刚";
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`;
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`;
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`;
  } else {
    return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
  }
};

// 刷新数据（暴露给父组件调用）
const refresh = () => {
  loadNotificationList();
};

// 组件挂载
onMounted(() => {
  loadNotificationList();
});

// 暴露方法给父组件
defineExpose({
  refresh
});
</script>

<style scoped lang="scss">
// 响应式设计
@media (width <= 768px) {
  .notification-list-container {
    .toolbar {
      flex-direction: column;
      gap: 12px;
      align-items: stretch;

      .toolbar-left,
      .toolbar-right {
        justify-content: center;
        width: 100%;
      }
    }

    .notifications-list {
      .notification-item {
        flex-wrap: wrap;
        padding: 12px;

        .item-content {
          order: 3;
          width: 100%;
        }

        .item-right {
          flex-direction: row;
          align-items: center;
          justify-content: space-between;
          order: 4;
          width: 100%;
          margin-top: 8px;
        }
      }
    }
  }
}

.notification-list-container {
  // 工具栏
  .toolbar {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 12px 16px;
    margin-bottom: 12px;
    background: #fff;
    border-radius: 8px;
    box-shadow: 0 1px 3px rgb(0 0 0 / 5%);

    .toolbar-left {
      :deep(.el-radio-group) {
        .el-radio-button__inner {
          padding: 8px 16px;
          font-size: 13px;
        }

        .el-radio-button__original-radio:checked + .el-radio-button__inner {
          background: #7cb4fd;
          border-color: #7cb4fd;
        }
      }
    }

    .toolbar-right {
      display: flex;
      gap: 8px;

      .el-button {
        font-size: 13px;

        .el-icon {
          font-size: 14px;
        }
      }
    }
  }

  // 通知列表
  .notifications-list {
    .notification-item {
      position: relative;
      display: flex;
      gap: 12px;
      align-items: center;
      padding: 12px 16px;
      margin-bottom: 8px;
      cursor: pointer;
      background: #fff;
      border-radius: 8px;
      transition: all 0.2s ease;

      &:hover {
        background: #f8fafc;
        box-shadow: 0 2px 8px rgb(0 0 0 / 8%);
      }

      &.is-unread {
        background: #f0f9ff;

        &:hover {
          background: #e0f2fe;
        }
      }

      &:last-child {
        margin-bottom: 0;
      }

      // 未读指示器
      .unread-dot {
        position: absolute;
        top: 50%;
        left: 4px;
        width: 6px;
        height: 6px;
        background: #3b82f6;
        border-radius: 50%;
        transform: translateY(-50%);
      }

      // 头像
      .item-avatar {
        flex-shrink: 0;
        margin-left: 4px;
        cursor: pointer;
        transition: transform 0.2s ease;

        &:hover {
          transform: scale(1.08);
        }

        // 聚合头像
        .aggregated-avatars {
          position: relative;
          display: flex;
          width: 60px;
          height: 32px;

          .stacked-avatar {
            position: absolute;
            cursor: pointer;
            border: 2px solid #fff;
            box-shadow: 0 1px 4px rgb(0 0 0 / 10%);
            transition: transform 0.2s ease;

            &:hover {
              z-index: 10 !important;
              transform: scale(1.12);
            }

            &:nth-child(1) {
              left: 0;
            }

            &:nth-child(2) {
              left: 14px;
            }

            &:nth-child(3) {
              left: 28px;
            }
          }

          .remaining-count {
            position: absolute;
            right: -6px;
            bottom: -2px;
            z-index: 10;
            display: flex;
            align-items: center;
            justify-content: center;
            min-width: 18px;
            height: 18px;
            padding: 0 4px;
            font-size: 10px;
            font-weight: 600;
            color: #fff;
            background: #3b82f6;
            border: 2px solid #fff;
            border-radius: 9px;
          }
        }
      }

      // 内容区域
      .item-content {
        flex: 1;
        min-width: 0;
        overflow: hidden;

        .content-text {
          font-size: 14px;
          line-height: 1.6;
          color: #334155;

          .sender-name {
            font-weight: 600;
            color: #1e293b;
            cursor: pointer;
            transition: color 0.2s ease;

            &:hover {
              color: #3b82f6;
            }
          }
        }
      }

      // 右侧信息
      .item-right {
        display: flex;
        flex-shrink: 0;
        flex-direction: column;
        gap: 8px;
        align-items: flex-end;

        .meta-time {
          margin-top: 4px;
          font-size: 12px;
          color: #94a3b8;
          white-space: nowrap;
        }

        .item-actions {
          display: flex;
          gap: 4px;
          align-items: center;
          min-height: 24px;

          .read-text {
            padding: 4px 8px;
            font-size: 12px;
            color: #94a3b8;
          }

          .el-button {
            padding: 4px;

            .el-icon {
              font-size: 16px;
            }

            &.el-button--primary {
              color: #3b82f6;

              &:hover {
                color: #2563eb;
                background: #eff6ff;
              }
            }

            &.el-button--danger {
              color: #ef4444;

              &:hover {
                color: #dc2626;
                background: #fef2f2;
              }
            }
          }
        }
      }
    }
  }

  // 分页
  .pagination-wrapper {
    display: flex;
    justify-content: center;
    padding: 16px 0;

    :deep(.el-pagination) {
      .btn-prev,
      .btn-next,
      .el-pager li {
        &.is-active {
          color: #fff;
          background: #3b82f6;
        }
      }
    }
  }
}
</style>
